<script setup>
import { ref } from 'vue'
import { onMounted, onBeforeUnmount } from 'vue'
import { jsPlumb } from 'jsplumb'
import Locomotive from '@/assets/train/locomotive.webp'
import Fuel from '@/assets/train/fuel.webp'
import Wagon from '@/assets/train/wagon.webp'
import Converter from '@/assets/train/converter.webp'
import Tail from '@/assets/train/tail.webp'
import SuccessAudio from '@/assets/audios/greetings.mp3'
import FailAudio from '@/assets/audios/suggestion.mp3'
import fetchCoin from '@/utils/fetchCoin'
import CoinIcon from '@/components/icons/CoinIcon.vue'
import SpeakerIcon from '@/components/icons/SpeakerIcon.vue'

const audioUrl = import.meta.env.VITE_PART1_AUDIO_URL || ''
const fraction = defineModel('fraction', { type: Number })
const connections = defineModel('connections', { type: Array })
const coins = ref(0)
const correctArr = ref([])
const props = defineProps({
  questions: Array
})
const photoList = [
  {
    id: 'locomotive',
    src: Locomotive
  },
  {
    id: 'fuel',
    src: Fuel
  },
  {
    id: 'wagon',
    src: Wagon
  },
  {
    id: 'converter',
    src: Converter // 等背景图扣干净后可能需要修改后缀
  },
  {
    id: 'tail',
    src: Tail
  }
]

const findNumericVariable = (var1, var2) => {
  const isNumeric = (str) => /^[0-9]+$/.test(str)

  const isVar1Numeric = isNumeric(var1)
  const isVar2Numeric = isNumeric(var2)

  if (isVar1Numeric && !isVar2Numeric) {
    return [parseInt(var1)]
  } else if (!isVar1Numeric && isVar2Numeric) {
    return [parseInt(var2)]
  } else if (isVar1Numeric && isVar2Numeric) {
    return [parseInt(var1), parseInt(var2)] // 如果两个都是纯数字字符串，则返回两个
  } else {
    return null // 如果两个都不是纯数字字符串，则返回 null
  }
}

const fetchAudio = (content) => {
  console.log(content)
  if (content.includes('程序：')) {
    console.log(`${audioUrl}/adult/${content.replace('程序：', '')}.mp3`)
    const audio = new Audio(
      `${audioUrl}/adult/${content.replace('程序：', '').replace(/\?/g, '？').replace(/!/g, '！')}.mp3`
    )
    audio.play()
  } else if (content.includes('儿童：')) {
    const audio = new Audio(
      `${audioUrl}/boy/${content.replace('儿童：', '').replace(/\?/g, '？').replace(/!/g, '！')}.mp3`
    )
    audio.play()
  }
}

onMounted(async () => {
  console.log(props.questions)
  coins.value = await fetchCoin('1')
  console.log(coins.value)
  jsPlumb.ready(function () {
    jsPlumb.setContainer('diagramContainer')
    var common = {
      isSource: true,
      isTarget: true,
      connector: ['Straight']
    }
    photoList.map((item) => {
      jsPlumb.addEndpoint(
        item.id,
        {
          anchor: 'Right'
        },
        common
      )
    })
    props.questions.map((item) => {
      jsPlumb.addEndpoint(
        item.dialogueInnerId.toString(),
        {
          anchor: 'Left'
        },
        common
      )
    })
    jsPlumb.bind('connectionDragStop', function (info) {
      // locomotive 0
      // fuel 1
      // wagon 2
      // converter 3
      // tail 4
      const id1 = info.sourceId
      const id2 = info.targetId
      const temp = findNumericVariable(id1, id2) // 返回的是一个数组
      connections.value = jsPlumb.getConnections()
      // 有这么几种情况，只有没连上的时候会出现 source 和 target 为 null 的情况
      // 1 连对了，播放语音，加一个金币
      // 2 连错了，播放语音，减一个金币
      // 3 本来是对的，然后给取消掉了，播放语音，减一个金币
      // 4 本来是对的，然后给连错了，播放语音，减一个金币
      // 5 本来是对的，松开重新连同一个，不播放语音，不加金币
      // 6 本来是错的，然后给取消掉了，不播放语音，不加金币
      // 7 本来是错的，然后给连对了，播放语音，加一个金币
      // 8 本来是错的，松开重新连同一个，播放语音，减一个金币
      // 9 连到一半没连上，不播放语音，不加金币
      if (
        ((id1 === '0' || id1 === 'locomotive') && (id2 === 'locomotive' || id2 === '0')) ||
        ((id1 === '1' || id1 === 'fuel') && (id2 === 'fuel' || id2 === '1')) ||
        ((id1 === '2' || id1 === 'wagon') && (id2 === 'wagon' || id2 === '2')) ||
        ((id1 === '3' || id1 === 'converter') && (id2 === 'converter' || id2 === '3')) ||
        ((id1 === '4' || id1 === 'tail') && (id2 === 'tail' || id2 === '4'))
      ) {
        // 1 3 5 7
        if (info.source !== null && info.target !== null) {
          // 1 5 7
          if (!correctArr.value.includes(temp[0])) {
            // 1 7
            const audio = new Audio(SuccessAudio)
            audio.play()
            correctArr.value = correctArr.value.concat(temp)
            fraction.value++
          }
          // 5 不需要做任何操作
        } else {
          // 3
          const audio = new Audio(FailAudio)
          audio.play()
          correctArr.value = correctArr.value.filter((item) => item !== temp[0])
          fraction.value--
        }
      } else {
        console.log(info)
        // 2 4 6 8 9
        if (
          !['0', '1', '2', '3', '4', 'locomotive', 'fuel', 'wagon', 'converter', 'tail'].includes(
            info.targetId
          ) ||
          info.source === null ||
          info.target === null
        ) {
          // 6 9
          // 不需要做任何操作
        } else {
          // 2 4 8
          // 2 连错了，播放语音，减一个金币
          // 4 本来是对的，然后给连错了，播放语音，减一个金币
          // 8 本来是错的，松开重新连同一个，播放语音，减一个金币
          console.log(info)
          // 2
          const audio = new Audio(FailAudio)
          audio.play()
          fraction.value--
          // 这里判断是否是原来是对的，需要把原来对的位置的金币消失
          correctArr.value = []
          jsPlumb.getConnections().map((item) => {
            const { sourceId, targetId } = item
            const t = findNumericVariable(sourceId, targetId)
            if (
              ((sourceId === '0' || sourceId === 'locomotive') &&
                (targetId === 'locomotive' || targetId === '0')) ||
              ((sourceId === '1' || sourceId === 'fuel') &&
                (targetId === 'fuel' || targetId === '1')) ||
              ((sourceId === '2' || sourceId === 'wagon') &&
                (targetId === 'wagon' || targetId === '2')) ||
              ((sourceId === '3' || sourceId === 'converter') &&
                (targetId === 'converter' || targetId === '3')) ||
              ((sourceId === '4' || sourceId === 'tail') &&
                (targetId === 'tail' || targetId === '4'))
            ) {
              correctArr.value.push(t[0])
            }
          })
        }
      }
    })
  })
})

onBeforeUnmount(() => {
  jsPlumb.reset()
})
</script>
<template>
  <div style="z-index: 100">
    <div
      style="
        position: absolute;
        top: 0;
        right: 0;
        display: flex;
        align-items: center;
        justify-content: center;
      "
    >
      <coin-icon :size="64" />
      <span style="font-size: 36px; margin-left: 8px; color: white">{{
        coins + fraction < 0 ? '0' : coins + fraction
      }}</span>
    </div>
    <div id="diagramContainer" style="width: 100%; display: flex; z-index: 100">
      <div style="display: flex; flex-direction: column; justify-content: space-between">
        <div
          v-for="(item, index) in photoList"
          :key="index"
          :id="item.id"
          :style="{
            height: '112px', // 7*16=112
            width: '240px', // 15*16=240
            backgroundImage: `url(${item.src})`,
            backgroundRepeat: 'no-repeat',
            backgroundPosition: 'center',
            backgroundSize: 'contain'
          }"
        ></div>
      </div>
      <div
        style="
          margin-left: auto;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
        "
      >
        <div
          v-for="(item, index) in questions"
          :key="index"
          style="display: flex; align-items: center; justify-content: center"
        >
          <div
            :id="item.dialogueInnerId"
            style="
              padding: 0 20px;
              border: 2px solid #f55a36;
              border-radius: 20px;
              background-color: #ffe2b3;
              display: flex;
              flex-direction: column;
              width: 100%;
              align-items: center;
              justify-content: center;
            "
          >
            <div v-for="(content, index) in item.stem" :key="index">
              <span style="color: black; white-space: pre-line; font-size: 24px">{{
                content.replace(/程序：|儿童：/g, '')
              }}</span>
              <speaker-icon @click="fetchAudio(content)" />
            </div>
          </div>
          <div style="width: 28px">
            <coin-icon v-show="correctArr.includes(item.dialogueInnerId)" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped>
.base-border {
  background-color: #ffe2b3;
  border: 6px solid #f55a36;
  font-size: 28px;
  border-radius: 20px;
}
</style>
